package com.zsy._21生产者与消费者问题;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用 Condition 精准通知与唤醒，使线程顺序执行
 *
 * @author: zhangshuaiyin
 * @date: 2021/9/13 21:32
 */
public class LockDemo02 {

    public static void main(String[] args) {
        Data3 data = new Data3();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.printA();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.printB();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.printC();
            }
        }, "C").start();
    }
}

class Data3 {
    final Lock lock = new ReentrantLock();
    final Condition conditionA = lock.newCondition();
    final Condition conditionB = lock.newCondition();
    final Condition conditionC = lock.newCondition();
    /**
     * number = 1 A 执行
     * number = 2 B 执行
     * number = 3 C 执行
     */
    private int number = 1;

    public void printA() {
        try {
            lock.lock();
            while (number != 1) {
                // A 等待
                conditionA.await();
            }
            System.out.println(Thread.currentThread().getName() + " -> A");
            number = 2;
            // 唤醒 B
            conditionB.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        try {
            lock.lock();
            while (number != 2) {
                // B 等待
                conditionB.await();
            }
            System.out.println(Thread.currentThread().getName() + " -> B");
            number = 3;
            // 唤醒 C
            conditionC.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        try {
            lock.lock();
            while (number != 3) {
                // C 等待
                conditionC.await();
            }
            System.out.println(Thread.currentThread().getName() + " -> C");
            number = 1;
            // 唤醒 A
            conditionA.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
